import { ElectronicLockMessageDTO, DispatchDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { SiteDTO, ElectronicLockDTO, ServiceProxy, UserInfoDTO } from '@shared/service-proxy/service-proxies';
import { loadModules } from 'esri-loader';
import esri = __esri;
import { ElementRef, ViewChild } from "@node_modules/@angular/core";
import { AppConsts } from "@shared/AppConsts";

@Component({
  selector: 'app-lock-locate',
  templateUrl: './lock-locate.component.html',
  styleUrls: ['./lock-locate.component.less']
})
export class LockLocateComponent extends AppComponentBase implements OnInit {
  @ViewChild('mapViewNode') private mapViewEl: ElementRef;

  siteId = '';
  lockState: string = '';
  lockNo: string = '';
  startTime: null;
  endTime: null;
  sites: SiteDTO[];
  lock: ElectronicLockDTO;
  states = [];
  onlinePonits: ElectronicLockDTO[] = [];
  locks: ElectronicLockDTO[] = [];
  tempLocks: ElectronicLockDTO[];
  currentUser = this.appSession.user;
  sitePoints: Array<any> = [];
  lockPoints: Array<any> = [];
  legendShow: boolean = false;
  timer: any;
  mapModules: Array<any> = [];
  mapView: esri.MapView;

  constructor(
    injector: Injector,
    private _service: ServiceProxy) {
    super(injector);
  }


  ngOnInit() {
    this.getSites();
    this.setMapView();
    $(window).resize(() => {
      this.setMapView();
    });
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }
  
  getSites() {
    this._service.getAllSitesBySiteUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
      this.sites.map(m => {
        this.sitePoints.push([m.lng, m.lat]);
      });
      const site = this.sites[0];
      if (site) {
        this._center = [site.lng, site.lat];
      }
      this.initializeMap();
    })
  }

  setLocks(siteId?: string) {
    //site 站点
    this.lockPoints = [];
    this.onlinePonits = [];
    this._service.getListElectronicLockAndMessageUsingGET(siteId).subscribe(result => {
      this.onlinePonits = result.result.fieldList;
      this.lockPoints = result.result.fieldList.filter(m => m.electronicLockMessageDTO != null
        && m.electronicLockMessageDTO.latitude != 0 && m.electronicLockMessageDTO.longitude != 0);
      if (this.lockNo != '') {
        clearInterval(this.timer);
        this.timer = setInterval(() => {
          this.drawMap();
        }, 20000);
      } else {
        clearInterval(this.timer);
        this.drawMap();
      }
    })
  }

  setMapView() {
    const $mapview = $('.esri-view');
    $mapview.height($(window).innerHeight() - 240);
  }

  changeSelect() {
    clearInterval(this.timer);
    this.lockNo = "";
    if (this.siteId) {
      const findList = this.sites.filter(m => m.id == this.siteId);
      const site = findList[0];
      this.mapView.graphics.removeAll();
      this.sitePoints = [];
      this.sitePoints.push([site.lng, site.lat]);
      this._center = [site.lng, site.lat];
      this.setLocks(site.id);

    } else {
      this.mapView.graphics.removeAll();
      this.sitePoints = [];
      this.sites.map(m => {
        this.sitePoints.push([m.lng, m.lat]);
      });
      this.setLocks();
    }
  }


  selectLock() {
    this.lock = this.onlinePonits.find(m => m.lockNo == this.lockNo);
    this.siteId = this.lock.siteId;
    clearInterval(this.timer);
    this.getLockNow();
    this.timer = setInterval(() => {
      this.getLockNow();
    }, 20000);
  }

  getLockNow() {
    this._service.getLastAddressByLockNoUsingGET(this.lock.lockNo).subscribe(m => {
      if (m.result) {
        this._center = [m.result.longitude, m.result.latitude];
        this.drawMap();
      }
      else {
        this.message.info(this.l("no_have_lock_message"));
      }
    })
  }


  reset() {
    this.siteId = '';
    this.lockState = '';
    this.lockNo = '';
  }

  async initializeMap() {
    try {
      const [
        Map,
        MapView,
        ScaleBar,
        TileLayer,
        Graphic] = this.mapModules = await loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/widgets/ScaleBar',
          'esri/layers/TileLayer',
          'esri/Graphic',
          'dojo/domReady!'
        ], {
            url: AppConsts.arcgisMapUrl, css: AppConsts.arcgisStyleUrl
          });

      this.mapView = new MapView({
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: new Map({
          // basemap: this._basemap,
          layers: new TileLayer({
            url: AppConsts.arcgisMapServerUrl
          })
        })
      });

      this.mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: this.mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        this.mapView.ui.add(scaleBar, "bottom-left");

        if (this.currentUser.siteId) {
          this.siteId = this.currentUser.siteId;
          this.setLocks(this.siteId);
        } else {
          this.setLocks();
        }
      });
    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }


  drawMap() {
    const [
      Map,
      MapView,
      ScaleBar,
      TileLayer,
      Graphic] = this.mapModules;
    this.mapView.center = this._center;
    const points = {
      type: "multipoint", // autocasts as new Point()
      points: this.sitePoints
    };
    // Create a symbol for drawing the point
    const markerSymbol = {
      type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
      url: "/assets/images/icon-flag.png",
      width: "24px",
      height: "24px",
      xoffset: "9px",
      yoffset: "10px"
    };


    // Create a graphic and add the geometry and symbol to it
    const pointGraphic = new Graphic({
      geometry: points,
      symbol: markerSymbol
    });

    // Create a symbol for drawing the point
    const lockMarkerSymbol = {
      type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
      url: "/assets/images/icon-location.png",
      width: "25px",
      height: "25px",
      yoffset: "12px"
    };
    if (this.lockPoints.length) {
      const lockPointGraphic: Array<any> = [];
      this.lockPoints.map((value, index, array) => {
        if (!value.dispatchDTO) {
          value.dispatchDTO = new DispatchDTO();
        }
        var msg = ""
        if (!value.electronicLockMessageDTO) {
          value.electronicLockMessageDTO = new ElectronicLockMessageDTO();
        } else {
          if (value.electronicLockMessageDTO.lockStickStatus) {
            msg += this.l('warn_lever_shearing') + "-";
          }
          if (value.electronicLockMessageDTO.lockStickStatus) {
            msg += this.l('warn_lever_shearing') + "-";
          }
          if (value.electronicLockMessageDTO.volt < 3450) {
            msg += this.l('warn_lvd') + "-"
          }
          if (value.electronicLockMessageDTO.outerStatus) {
            msg += this.l('warn_disassemble_bonnet') + "-"
          }
          if (value.electronicLockMessageDTO.gpsStatus) {
            msg += this.l('warn_gps_lost') + "-"
          }
          if (value.electronicLockMessageDTO.isLocked) {
            msg += this.l('lockset_lock_success') + "-";
          } else {
            msg += this.l('lockset_unlock_success') + "-";
          }
          msg += this.l('lvd_value') + value.electronicLockMessageDTO.volt + this.l('millivolt');
        }

        const dispathch = {
          containerCode: value.dispatchDTO.containerCode,
          lockCode: value.dispatchDTO.lockCode,
          containerStatusName: msg,
          routeCode: value.dispatchDTO.routeCode,
          launchsiteName: value.dispatchDTO.launchsiteName,
          destinationsiteName: value.dispatchDTO.destinationsiteName,
          platenumber: value.dispatchDTO.platenumber,
          latitude: value.electronicLockMessageDTO.latitude,
          longitude: value.electronicLockMessageDTO.longitude,
          speed: value.electronicLockMessageDTO.speed,
          time: value.electronicLockMessageDTO.time
        };


        lockPointGraphic[index] = new Graphic({
          geometry: {
            type: "point",  // autocasts as new Point()
            longitude: value.electronicLockMessageDTO.longitude,
            latitude: value.electronicLockMessageDTO.latitude
          },
          symbol: lockMarkerSymbol,

          attributes: dispathch,
          popupTemplate: { // autocasts as new PopupTemplate()
            title: "{containerCode}",
            content: [{
              type: "fields",
              fieldInfos: [{
                fieldName: "containerCode",
                label: this.l("container_no")
              }, {
                fieldName: "lockCode",
                label: this.l("lockset_no")
              }, {
                fieldName: "containerStatusName",
                label: this.l("lockset_state")
              }, {
                fieldName: "routeCode",
                label: this.l("path_no")
              }, {
                fieldName: "launchsiteName",
                label: this.l("start_site")
              }, {
                fieldName: "destinationsiteName",
                label: this.l("end_site")
              }, {
                fieldName: "platenumber",
                label: this.l("car_no")
              }, {
                fieldName: "longitude",
                label: this.l("longitude")
              }, {
                fieldName: "latitude",
                label: this.l("latitude")
              }, {
                fieldName: "time",
                label: this.l("get_date")
              }, {
                fieldName: "speed",
                label: this.l("speed")
              }]
            }]
          }
        });
      });
      this.mapView.graphics.addMany(lockPointGraphic);
    }
    if (this.sitePoints.length) {
      this.mapView.graphics.add(pointGraphic);
    }


  }


}
